package com.wwm.springcloud.authservice.service.extend;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

/**
 * @author wuwanming
 */
public class BwDaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
{
    private PasswordEncoder passwordEncoder;
    private String userNotFoundEncodedPassword;
    private SaltSource saltSource;
    private UserDetailsService userDetailsService;

    public BwDaoAuthenticationProvider()
    {
        //密码默认不加密，需要重写
        this.setPasswordEncoder(new PlaintextPasswordEncoder());
    }

    /**
     * 密码验证
     * @param userDetails
     * @param authentication
     * @throws AuthenticationException
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
    {
        Object salt = null;
        if(this.saltSource != null)
        {
            salt = this.saltSource.getSalt(userDetails);
        }

        if(authentication.getCredentials() == null)
        {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
        else
        {
            //密码判断
            String presentedPassword = authentication.getCredentials().toString();
            if(!this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt))
            {
                this.logger.debug("Authentication failed: password does not match stored value");
                throw new BadCredentialsException("输入密码错误");
            }
        }
    }

    @Override
    protected void doAfterPropertiesSet() throws Exception
    {
        Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
    }

    /**
     * 用户认证-根据用户名获取用户信息
     * retrieveUser是抽象方法，通过子类来实现获取用户的信息,以UserDetails接口形式返回
     * @param username
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
    {
        UserDetails loadedUser;
        try
        {
            loadedUser = this.getUserDetailsService().loadUserByUsername(username);
        }
        catch (UsernameNotFoundException var6)
        {
            if(authentication.getCredentials() != null)
            {
                String presentedPassword = authentication.getCredentials().toString();
                this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, null);
            }

            throw var6;
        }
        catch (Exception var7)
        {
            throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
        }

        if(loadedUser == null)
        {
            throw new InternalAuthenticationServiceException("认证失败！");
        }
        else
        {
            return loadedUser;
        }
    }

    public void setPasswordEncoder(Object passwordEncoder)
    {
        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
        if(passwordEncoder instanceof PasswordEncoder)
        {
            this.setPasswordEncoder((PasswordEncoder)passwordEncoder);
        }
        else if(passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder)
        {
            final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder)passwordEncoder;
            this.setPasswordEncoder(new PasswordEncoder()
            {
                @Override
                public String encodePassword(String rawPass, Object salt)
                {
                    this.checkSalt(salt);
                    return delegate.encode(rawPass);
                }

                @Override
                public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
                    this.checkSalt(salt);
                    return delegate.matches(rawPass, encPass);
                }

                private void checkSalt(Object salt) {
                    Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
                }
            });
        } else {
            throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");
        }
    }

    private void setPasswordEncoder(PasswordEncoder passwordEncoder)
    {
        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
        this.userNotFoundEncodedPassword = passwordEncoder.encodePassword("userNotFoundPassword", null);
        this.passwordEncoder = passwordEncoder;
    }

    protected PasswordEncoder getPasswordEncoder() {
        return this.passwordEncoder;
    }

    public void setSaltSource(SaltSource saltSource) {
        this.saltSource = saltSource;
    }

    protected SaltSource getSaltSource() {
        return this.saltSource;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected UserDetailsService getUserDetailsService() {
        return this.userDetailsService;
    }
}
